<?php

namespace App\Http\Controllers\Guest;

use App\Http\Controllers\Controller;
use App\Models\Task;
use App\Models\TaskApplication;
use App\Models\Freelancer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;

class TaskApplicationController extends Controller
{
    /**
     * 通过二维码获取任务详情
     */
    public function getTaskByCode(Request $request, $code)
    {
        $task = Task::where('qr_code', $code)
            ->where('status', 'published')
            ->with(['tenant:id,name,logo'])
            ->first();

        if (!$task) {
            return response()->json([
                'success' => false,
                'message' => '任务不存在或已下线'
            ], 404);
        }

        // 检查任务是否还在招募期内
        if ($task->application_deadline && now() > $task->application_deadline) {
            return response()->json([
                'success' => false,
                'message' => '任务报名已截止'
            ], 400);
        }

        // 检查是否还有名额
        if ($task->max_applicants && $task->applications()->count() >= $task->max_applicants) {
            return response()->json([
                'success' => false,
                'message' => '报名人数已满'
            ], 400);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'task' => [
                    'id' => $task->id,
                    'title' => $task->title,
                    'description' => $task->description,
                    'type' => $task->type,
                    'location' => $task->location,
                    'start_date' => $task->start_date,
                    'end_date' => $task->end_date,
                    'salary' => $task->salary,
                    'salary_type' => $task->salary_type,
                    'requirements' => $task->requirements,
                    'benefits' => $task->benefits,
                    'contact_info' => $task->contact_info,
                    'application_deadline' => $task->application_deadline,
                    'max_applicants' => $task->max_applicants,
                    'current_applicants' => $task->applications()->count(),
                    'tenant' => $task->tenant,
                    'created_at' => $task->created_at,
                ]
            ]
        ]);
    }

    /**
     * 提交任务报名
     */
    public function apply(Request $request, $code)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'email' => 'required|email|max:255',
            'id_card' => 'required|string|size:18',
            'real_name' => 'required|string|max:255',
            'gender' => 'required|in:male,female',
            'birth_date' => 'required|date',
            'address' => 'required|string|max:500',
            'experience' => 'sometimes|string|max:2000',
            'skills' => 'sometimes|array',
            'skills.*' => 'string|max:100',
            'education' => 'sometimes|in:high_school,college,bachelor,master,doctor',
            'emergency_contact' => 'required|string|max:255',
            'emergency_phone' => 'required|string|max:20',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $task = Task::where('qr_code', $code)
            ->where('status', 'published')
            ->first();

        if (!$task) {
            return response()->json([
                'success' => false,
                'message' => '任务不存在或已下线'
            ], 404);
        }

        // 检查任务是否还在招募期内
        if ($task->application_deadline && now() > $task->application_deadline) {
            return response()->json([
                'success' => false,
                'message' => '任务报名已截止'
            ], 400);
        }

        // 检查是否还有名额
        if ($task->max_applicants && $task->applications()->count() >= $task->max_applicants) {
            return response()->json([
                'success' => false,
                'message' => '报名人数已满'
            ], 400);
        }

        // 检查是否已经报名过（通过手机号或身份证号）
        $existingApplication = TaskApplication::where('task_id', $task->id)
            ->where(function ($query) use ($request) {
                $query->where('phone', $request->phone)
                      ->orWhere('id_card', $request->id_card);
            })
            ->first();

        if ($existingApplication) {
            return response()->json([
                'success' => false,
                'message' => '您已经报名过此任务'
            ], 400);
        }

        try {
            // 查找或创建自由职业者记录
            $freelancer = Freelancer::where(function ($query) use ($request) {
                $query->where('phone', $request->phone)
                      ->orWhere('id_card', $request->id_card)
                      ->orWhere('email', $request->email);
            })->first();

            if (!$freelancer) {
                // 创建新的自由职业者记录
                $freelancer = Freelancer::create([
                    'name' => $request->name,
                    'phone' => $request->phone,
                    'email' => $request->email,
                    'id_card' => $request->id_card,
                    'real_name' => $request->real_name,
                    'gender' => $request->gender,
                    'birth_date' => $request->birth_date,
                    'address' => $request->address,
                    'skills' => $request->skills ? json_encode($request->skills) : null,
                    'education' => $request->education,
                    'status' => 'active', // C端用户直接激活
                    'verification_status' => Freelancer::VERIFICATION_PENDING,
                    'id_card_recognition_status' => Freelancer::RECOGNITION_PENDING,
                    'face_recognition_status' => Freelancer::RECOGNITION_PENDING,
                    'source' => 'qr_application', // 标记来源
                ]);
            } else {
                // 更新现有自由职业者信息
                $freelancer->update([
                    'name' => $request->name,
                    'address' => $request->address,
                    'skills' => $request->skills ? json_encode($request->skills) : $freelancer->skills,
                    'education' => $request->education ?: $freelancer->education,
                ]);
            }

            // 创建任务报名记录
            $application = TaskApplication::create([
                'task_id' => $task->id,
                'freelancer_id' => $freelancer->id,
                'tenant_id' => $task->tenant_id,
                'name' => $request->name,
                'phone' => $request->phone,
                'email' => $request->email,
                'id_card' => $request->id_card,
                'real_name' => $request->real_name,
                'gender' => $request->gender,
                'birth_date' => $request->birth_date,
                'address' => $request->address,
                'experience' => $request->experience,
                'skills' => $request->skills ? json_encode($request->skills) : null,
                'education' => $request->education,
                'emergency_contact' => $request->emergency_contact,
                'emergency_phone' => $request->emergency_phone,
                'status' => 'pending',
                'applied_at' => now(),
                'source' => 'qr_code',
            ]);

            return response()->json([
                'success' => true,
                'message' => '报名成功，请等待审核',
                'data' => [
                    'application_id' => $application->id,
                    'application_number' => $application->application_number,
                    'status' => $application->status,
                    'applied_at' => $application->applied_at,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '报名失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 查询报名状态
     */
    public function checkStatus(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'application_number' => 'sometimes|string',
            'phone' => 'sometimes|string',
            'id_card' => 'sometimes|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $query = TaskApplication::with(['task:id,title,status', 'tenant:id,name']);

        if ($request->application_number) {
            $query->where('application_number', $request->application_number);
        } elseif ($request->phone) {
            $query->where('phone', $request->phone);
        } elseif ($request->id_card) {
            $query->where('id_card', $request->id_card);
        } else {
            return response()->json([
                'success' => false,
                'message' => '请提供报名编号、手机号或身份证号'
            ], 400);
        }

        $applications = $query->orderBy('created_at', 'desc')->get();

        if ($applications->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => '未找到相关报名记录'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'applications' => $applications->map(function ($app) {
                    return [
                        'id' => $app->id,
                        'application_number' => $app->application_number,
                        'task_title' => $app->task->title,
                        'tenant_name' => $app->tenant->name,
                        'status' => $app->status,
                        'status_text' => $app->getStatusText(),
                        'applied_at' => $app->applied_at,
                        'reviewed_at' => $app->reviewed_at,
                        'review_note' => $app->review_note,
                    ];
                })
            ]
        ]);
    }

    /**
     * 获取任务统计信息（公开信息）
     */
    public function getTaskStats($code)
    {
        $task = Task::where('qr_code', $code)
            ->where('status', 'published')
            ->first();

        if (!$task) {
            return response()->json([
                'success' => false,
                'message' => '任务不存在或已下线'
            ], 404);
        }

        $stats = [
            'total_applications' => $task->applications()->count(),
            'approved_applications' => $task->applications()->where('status', 'approved')->count(),
            'pending_applications' => $task->applications()->where('status', 'pending')->count(),
            'max_applicants' => $task->max_applicants,
            'remaining_slots' => $task->max_applicants ? max(0, $task->max_applicants - $task->applications()->count()) : null,
            'application_deadline' => $task->application_deadline,
            'is_deadline_passed' => $task->application_deadline ? now() > $task->application_deadline : false,
        ];

        return response()->json([
            'success' => true,
            'data' => $stats
        ]);
    }
}
